package org.jeecg.glr.iframe.controller;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.SysConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.glr.entity.GlrSensorData;
import org.jeecg.glr.entity.GlrVideo;
import org.jeecg.glr.iframe.service.IGlrIframeVideoMonitoringService;
import org.jeecg.glr.iframe.util.AjaxJson;
import org.jeecg.glr.service.*;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.PositionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.jeecg.common.constant.CommonConstant.St_Access_Token;

@Slf4j
@Controller
@RequestMapping("/iframeGlr/glrIframeMain")
public class GlrIframeMainController extends JeecgController<GlrVideo, IGlrVideoService> {

    @Autowired
    private IGlrLedService glrLedService;

    @Resource
    IGlrGatewayService glrGatewayService;

    @Autowired
    private IGlrRadioService glrRadioService;
    @Autowired
    private IGlrLightService glrLightService;
    @Autowired
    private IGlrFaultAlermService glrFaultAlermService;


    @Autowired
    private IGlrSensorService glrSensorService;

    @Autowired
    private IGlrVideoService glrVideoService;

    @Autowired
    private IGlrVideoYsService glrVideoYsService;
    @Autowired
    @Lazy
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    @Lazy
    private RedisUtil redisUtil;
    @Value("${glr.path.vue_url}")
    private String vue_url;

    @Autowired
    private IGlrIframeVideoMonitoringService glrIframeVideoMonitoringService;

    /**
     * 人脸检测结果一列
     *
     * @return
     */
    @RequestMapping("/index")
    public String list(Model model, HttpServletRequest request) throws Exception {
        LoginUser loginUser= glrIframeVideoMonitoringService.updateUserInfo(request);
        if(loginUser==null){
            return "redirect:"+vue_url;
        }
        model.addAttribute("AccessToken",request.getParameter(St_Access_Token));
        return "/main/index";
    }


    @RequestMapping("/getEchartLightPoweerDate")
    @ResponseBody
    public AjaxJson getEchartLightPoweerDate(Model model, HttpServletRequest request) throws Exception{
        LoginUser loginUser= glrIframeVideoMonitoringService.updateUserInfo(request);
        AjaxJson j = new AjaxJson();
        List<String> dateList = new ArrayList<>();
        List<Double> electricityList = new ArrayList<>();
        List<Double> avg_powerList = new ArrayList<>();
        List<String> day_economy_electricityList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        try {
            String stSql = "select \n" +
                    "sum(a.day_electricity) as day_electricity,\n" +
                    "sum(a.day_economy_electricity) as day_economy_electricity,\n" +
                    "AVG(a.avg_power) as avg_power,\n" +
                    "date_format(create_time, '%y%m%d') as create_date\n" +
                    "FROM glr_light_data a\n" +
                    "where 1=1 ";
            //月
            String yesterday1 = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getEndDayOfMonth());
            String yesterday2 = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getBeginDayOfMonth());
            String DataSql = stSql + " and date(create_time) between '" + yesterday2 + "' and '" + yesterday1 + "' group by date(create_time)";
            List<Map<String, Object>> ss = glrVideoYsService.doGetListForJdbc(DataSql);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date d2 = simpleDateFormat.parse(yesterday2);
            Date d1 = simpleDateFormat.parse(yesterday1);
            Calendar dd1 = Calendar.getInstance();//定义日期实例
            dd1.setTime(d1);//设置日期起始时间
            dd1.add(Calendar.HOUR, 1);

            Calendar dd2 = Calendar.getInstance();//定义日期实例
            dd2.setTime(d2);//设置日期起始时间


            while (dd2.getTime().before(dd1.getTime())) {//判断是否到结束日期
                String str = new SimpleDateFormat("yyyyMMdd").format(dd2.getTime());
                str = str.substring(2);
                boolean bfind = false;
                for (Map<String, Object> ss_1 : ss) {
                    String create_date = ss_1.get("create_date").toString();
                    String day_electricity = ss_1.get("day_electricity").toString();
                    String avg_power = ss_1.get("day_electricity").toString();
                    String day_economy_electricity = ss_1.get("day_economy_electricity").toString();
                    if (create_date.equals(str)) {
                        bfind = true;
                        dateList.add(create_date);
                        electricityList.add(Math.ceil(Double.parseDouble(day_electricity)));
                        avg_powerList.add(Math.ceil(Double.parseDouble(avg_power)));
                        day_economy_electricityList.add(day_economy_electricity);
                        break;
                    }
                }
                if (bfind) {

                } else {
                    electricityList.add(0d);
                    avg_powerList.add(0d);
                    day_economy_electricityList.add("0");
                    dateList.add(str);
                }
                dd2.add(Calendar.DATE, 1);//进行当前日期月份加1
            }

            double dayelectricity = 0;
            double day_economy_electricity = 0;
            for (int i = 0; i < electricityList.size(); i++) {
                dayelectricity = dayelectricity + electricityList.get(i);
                day_economy_electricity = day_economy_electricity + Double.parseDouble(day_economy_electricityList.get(i));
            }
            int jieyuemenghao = (int) (day_economy_electricity / (day_economy_electricity + dayelectricity) * 100);

            map.put("dateList", dateList);
            map.put("electricityList", electricityList);
            map.put("avg_powerList", avg_powerList);
            map.put("jieyuemenghao", jieyuemenghao);
            j.setAttributes(map);
        } catch (Exception ex) {
            j.setSuccess(false);
            ex.printStackTrace();
        }
        return j;
    }

    /**
     * 取所有传感器
     *
     * @param model
     * @return
     */
    @RequestMapping("/getMainData")
    @ResponseBody
    public AjaxJson getMainData(Model model,HttpServletRequest request) throws Exception{
        AjaxJson j = new AjaxJson();
        String codeSql="";
        String sql1 = "select 'gateway'as a0,count(*) as a1,sum(if(current_work_status='Y',1,0)) as a2 from glr_gateway where 1=1 "+codeSql;
        String sql2 = "select 'light'as a0,count(*) as a1,0 as a2 from glr_light where 1=1 "+codeSql;
        String sql3 = "select 'led'as a0,count(*) as a1,sum(if(status='Y',1,0)) as a2 from glr_led where 1=1 "+codeSql;
        String sql4 = "select 'sensor'as a0,count(*) as a1,sum(if(status='Y',1,0)) as a2 from glr_sensor where 1=1 "+codeSql;
        String sql5 = "select 'video'as a0,count(*) as a1,sum(if(equipment_status='Y',1,0)) as a2 from glr_video where 1=1 "+codeSql;
        String sql6 = "select 'radio'as a0,count(*) as a1,sum(if(status<>'Offline',1,0)) as a2 from glr_radio where 1=1 "+codeSql;
        String sql7 = "select 'fault_alerm'as a0,count(*) as a1,0 as a2 from glr_fault_alerm where 1=1 and status<>'"+ GLRConstant.YN_Y +"'  GROUP BY lig_code,device_id,device_type "+codeSql;
        int year = DateUtils.getYear();
        String sql8 = "select 'light_data' as a0,sum(day_Electricity) as a1,avg(avg_power) as a2 from glr_light_data where date_format(create_time, '%Y')='" + year + "'" +codeSql;
        String stsql = sql1 + "\n union \n" + sql2 + "\n union \n" + sql3 + "\n union \n" + sql4 + "\n union \n" + sql5 + "\n union \n" + sql6 + "\n union \n" + sql7 + "\n union \n" + sql8;
        List<Map<String, Object>> dataList = glrVideoYsService.doGetListForJdbc(stsql);
        //总数
        int ledcount = 0;
        int gatewaycount = 0;
        int sensorcount = 0;
        int videocount = 0;
        int radiocount = 0;
        //在线
        int zaixian_led = 0;
        int zaixian_gateway = 0;
        int zaixian_sensor = 0;
        int zaixian_video = 0;
        int zaixian_radio = 0;

        int guzhang_count = 0;

        int power_sum = 0;
        int power_avg = 0;

        int all_count = 0;
        int ligth_count = 0;
        for (Map<String, Object> a1 : dataList) {
            String sta0 = "0";
            if(a1.get("a0")!=null){
                sta0= a1.get("a0").toString();
            }
            String sta1 = "0";
            if(a1.get("a1")!=null){
                sta1= a1.get("a1").toString();
            }
            String sta2 = "0";
            if(a1.get("a2")!=null){
                sta2= a1.get("a2").toString();
            }
            int count = (int) Double.parseDouble(sta1);
            int icounta2 = (int) Double.parseDouble(sta2);
            if ("sensor".equals(sta0)) {
                sensorcount = count;
                zaixian_sensor = icounta2;
                all_count = all_count + count;
            }
            if ("led".equals(sta0)) {
                ledcount = count;
                zaixian_led = icounta2;
                all_count = all_count + count;
            }
            if ("video".equals(sta0)) {
                videocount = count;
                zaixian_video = icounta2;
                all_count = all_count + count;
            }
            if ("radio".equals(sta0)) {
                radiocount = count;
                zaixian_radio = icounta2;
                all_count = all_count + count;
            }

            if ("gateway".equals(sta0)) {
                gatewaycount = count;
                zaixian_gateway = icounta2;
                all_count = all_count + count;
            }
            if ("light".equals(sta0)) {
                ligth_count = count;
                all_count = all_count + count;
            }

            if ("fault_alerm".equals(sta0)) {
                guzhang_count = count;
            }
            if ("light_data".equals(sta0)) {
                power_sum = count;
                power_avg = icounta2;
            }
        }

        int zaixianlv = (int) (Double.valueOf(zaixian_gateway + zaixian_radio + zaixian_video + zaixian_led + zaixian_sensor) / Double.valueOf(all_count) * 100);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("all_count", all_count);  //所有的设备数
        map.put("gatewaycount", gatewaycount);
        map.put("zaixian_gateway", zaixian_gateway);

        map.put("zaixian_radio", zaixian_radio);
        map.put("radiocount", radiocount);

        map.put("zaixian_video", zaixian_video);
        map.put("videocount", videocount);

        map.put("zaixian_led", zaixian_led);
        map.put("ledcount", ledcount);

        map.put("sensorcount", sensorcount);
        map.put("zaixian_sensor", zaixian_sensor);

        map.put("zaixianlv", zaixianlv);
        map.put("guzhang_count", guzhang_count);


        map.put("power_sum", power_sum);  //当年总用量
        map.put("power_avg", power_avg);  //当年平均功率
        map.put("ligth_count", ligth_count);


        j.setAttributes(map);
        return j;
    }


    @RequestMapping("/getSenSor")
    public String getSenSor(Model model, HttpServletRequest request) throws Exception {
        GlrSensorData sensor = glrSensorService.getGlrSensorOne(null,request);
        sensor.setWindDirection(PositionUtil.getWindDirection(sensor.getWindDirection()));
        model.addAttribute("sensor", sensor);
        return "/main/mainSensor";
    }


}
